package cn.wawi.controller.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import com.wawi.common.ResultData;
import com.wawi.common.annotation.Permission;
import com.wawi.common.easyui.Tree;
import cn.wawi.controller.BaseController;
import cn.wawi.dao.sys.PrivilegeDao;
import cn.wawi.entity.sys.Privilege;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/sys_privilege")
public class PrivilegeController extends BaseController<Privilege>{
	
	@Resource
	protected PrivilegeDao<Privilege> privilegeDao;
	
	@Permission("sys:privilege:menu:view")
	@RequestMapping(value="/menu",method=RequestMethod.GET)
	public String menu() {
		return "sys/Privilege/menu";
	}
	/**
	 *主页
	 */
	@RequestMapping(value="/main",method=RequestMethod.GET)
	public String main() {
		return "sys/Privilege/main";
	}

	@ResponseBody
	@RequestMapping(value="/addPermission",method=RequestMethod.GET)
	public ResultData<Privilege> addPermission(Long pId){
		privilegeDao.saveOne(new Privilege("添加","add","添加",pId));
		privilegeDao.saveOne(new Privilege("删除","delete","删除",pId));
		privilegeDao.saveOne(new Privilege("修改","update","修改",pId));
		privilegeDao.saveOne(new Privilege("查看","view","查看",pId));
		return new ResultData<Privilege>();
	}
	
	/**
	 * 获取所有菜单树
	 */
	@ResponseBody
	@RequestMapping(value="/tree",method=RequestMethod.GET)
	public List<Tree> tree(){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("type", "F");
		List<Privilege> list = privilegeDao.findAll(map);
		List<Tree> tree=createTree(list,null);
		return tree;
	}
	/**
	 * 获取顶级菜单
	 */
	@ResponseBody
	@RequestMapping(value="/getTopMenu",method=RequestMethod.GET)
	public List<Tree> getTopMenu(){
		List<Privilege> list = privilegeDao.getTopMenu();
		List<Tree> tree=createTree(list,null);
		return tree;
	}
	public List<Tree> createTree(List<Privilege> list,Long pId){
		List<Tree> trees=new ArrayList<Tree>();
		for(Privilege d: list){
           if(pId==d.getParentId()){
        	   Tree tree=new Tree();
        	   tree.setId(d.getId());
        	   tree.setText(d.getName());
        	   tree.setIconCls(d.getIconCls());
        	   tree.getAttributes().put("pId", d.getParentId());
        	   tree.setChildren(createTree(list,d.getId()));
        	   trees.add(tree);
           }
		}
		return trees;
	}
}
